package com.robot.app;

import com.robot.models.BusinessConfig;
import com.robot.models.EventInfo;
import com.robot.models.OrderDetail;
import com.robot.models.v1.Demo1;
import com.robot.services.BusinessConfigService;
import com.robot.services.EventInfoService;
import com.robot.services.OrderDetailService;
import com.robot.util.Guid;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@RestController
@RequestMapping("/receiveFiles")
public class ReceiveFiles {

    @Autowired
    private EventInfoService eventInfoService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private BusinessConfigService businessConfigService;

    private final Logger log = Logger.getLogger(String.valueOf(this.getClass()));

    private String encoding = "GBK";
//    private String encoding = "UTF-8";

    /*
    *    http://localhost:8080/receiveFiles/api/v1/text?file=E:/lxg/loging_date.txt
    *    file：为参数名
    *    E:/lxg/loging_date.txt 为上传文件路径  注意格式|
     */
    @RequestMapping(value = {"/api/v1/text3"}, method = {RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    @Transactional
    public String add(@RequestParam("file") File file)  {
        String result = "0";
        String data = "";
        String[] str = {};
        InputStreamReader read = null;//考虑到编码格式
        try {
        read = new InputStreamReader(new FileInputStream(file), encoding);// 建立一个输入流对象reader
        BufferedReader br = new BufferedReader(read); // 建立一个对象，它把文件内容转成计算机能读懂的语言

        String line = "";
        while ((line = br.readLine()) != null) {
            data += line; // 一次读入一行数据
        }
        System.out.println(data);
        String s = new String(data.getBytes(), "UTF-8");
        str = s.split("#_#");
        // 把字符串转换为JSONArray对象
        JSONArray jsonArray = JSONArray.fromObject(str);
        if (jsonArray.size() > 0) {
            // 遍历 jsonarray 数组，把每一个对象转成 json 对象
            for (int i = 0; i < jsonArray.size(); i++) {
                Long EventId = Long.valueOf(Guid.getId());
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                EventInfo eventInfo = new EventInfo();
                eventInfo.setEventId(EventId);
                eventInfo.setEventIp(jsonObject.get("event_ip").toString());
                eventInfo.setWorkerId(jsonObject.get("worker_id").toString());
                eventInfo.setLoginDate(jsonObject.get("login_date").toString());
                eventInfo.setBusinessId(Integer.parseInt(jsonObject.get("business_id").toString()));
                eventInfoService.add(eventInfo);

                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setEventId(EventId);
                orderDetail.setItemVal(jsonObject.get("item_val").toString());
                orderDetail.setStatus(jsonObject.get("status").toString());
                orderDetail.setStatusTime(jsonObject.get("status_time").toString());
                orderDetail.setFailedReason(jsonObject.get("failed_reason").toString());
                orderDetail.setStartTime(jsonObject.get("start_time").toString());
                orderDetailService.add(orderDetail);
                result="1";
               }
            }
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
            result="数据不完整";
        }
            return result;
        }

    @RequestMapping(value = {"/api/v1/text1"}, method = {RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public String ceshi(@RequestParam("file") String file) throws  Exception {
        String result = "0";
        String[] str = {};
        System.out.println(file);
        String s = new String(file.getBytes(), "UTF-8");
        str = s.split("#_#");
        // 把字符串转换为JSONArray对象
        JSONArray jsonArray = JSONArray.fromObject(str);
        if (jsonArray.size() > 0) {
            // 遍历 jsonarray 数组，把每一个对象转成 json 对象
            for (int i = 0; i < jsonArray.size(); i++) {
                Long EventId = Long.valueOf(Guid.getId());
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                EventInfo eventInfo = new EventInfo();
                eventInfo.setEventId(EventId);
                eventInfo.setEventIp(jsonObject.get("event_ip").toString());
                eventInfo.setWorkerId(jsonObject.get("worker_id").toString());
                eventInfo.setLoginDate(jsonObject.get("login_date").toString());
                eventInfo.setBusinessId(Integer.parseInt(jsonObject.get("business_id").toString()));
                eventInfoService.add(eventInfo);

                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setEventId(EventId);
                orderDetail.setItemVal(jsonObject.get("item_val").toString());
                orderDetail.setStatus(jsonObject.get("status").toString());
                orderDetail.setStatusTime(jsonObject.get("status_time").toString());
                orderDetail.setFailedReason(jsonObject.get("failed_reason").toString());
                orderDetail.setStartTime(jsonObject.get("start_time").toString());
                orderDetailService.add(orderDetail);
                result ="1";
            }
        }
        return result;
    }

     //服务器地址  http://132.108.200.88:8011/api/v1/text
    @RequestMapping(value = {"/api/v1/text"}, method = {RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    @Transactional
    public String add3(@RequestParam("file") String file)  {
        String result = "0";
        System.out.println(file);
        String s = null;
        String[] str = {};
        try {
            s = new String(file.getBytes(), "UTF-8");
            str = s.split("#_#");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            result="数据读取错误";
            log.info(file+":"+result);
            return  result;
        }
//        String data = "";
//        String[] str = {};
        List<Demo1> list = new ArrayList();
//        InputStreamReader read = null;//考虑到编码格式
//        try {
//            read = new InputStreamReader(new FileInputStream(file), encoding);// 建立一个输入流对象reader
//            BufferedReader br = new BufferedReader(read); // 建立一个对象，它把文件内容转成计算机能读懂的语言
//            String line = "";
//            while ((line = br.readLine()) != null) {
//                data += line; // 一次读入一行数据
//            }
//
//            System.out.println(data);
//            String s = new String(data.getBytes(), "UTF-8");
//            str = s.split("#_#");
//            read.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            result="数据读取错误";
//            log.info(data+":"+result);
//            return  result;
//        }

        // 把字符串转换为JSONArray对象
        JSONArray jsonArray = JSONArray.fromObject(str);
        if (jsonArray.size() > 0) {
            // 遍历 jsonarray 数组，把每一个对象转成 json 对象
            for (int i = 0; i < jsonArray.size(); i++) {
                try{
                    Demo1 dame1 = new Demo1();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dame1.setEventId(Long.valueOf(Guid.getId()));
                    dame1.setEventIp(jsonObject.get("event_ip").toString());
                    dame1.setWorkerId(jsonObject.get("worker_id").toString());
                    dame1.setLoginDate(jsonObject.get("login_date").toString());
                    dame1.setBusinessId(Integer.parseInt(jsonObject.get("business_id").toString()));
                    dame1.setItemVal(jsonObject.get("item_val").toString());
                    dame1.setStatus(jsonObject.get("status").toString());
                    dame1.setStatusTime(jsonObject.get("status_time").toString());
                    dame1.setFailedReason(jsonObject.get("failed_reason").toString());
                    dame1.setStartTime(jsonObject.get("start_time").toString());
                    dame1.setItemKey(jsonObject.get("item_key").toString());
                    list.add(dame1);
                }catch (Exception e) {
                    e.printStackTrace();
                    result="json格式错误";
                    log.info(file+":"+result);
                    return  result;
                }
            }
        }

        for(Demo1 l:list){
            if(l.getStatus()!="" && !l.getStatus().equals("")){
                EventInfo eventInfo = new EventInfo();
                eventInfo.setEventId(l.getEventId());
                eventInfo.setEventIp(l.getEventIp());
                eventInfo.setWorkerId(l.getWorkerId());
                eventInfo.setLoginDate(l.getLoginDate());
                eventInfo.setBusinessId(l.getBusinessId());
                eventInfoService.add(eventInfo);

                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setEventId(l.getEventId());
                orderDetail.setItemVal(l.getItemVal());
                orderDetail.setStatus(l.getStatus());
                orderDetail.setStatusTime(l.getStatusTime());
                orderDetail.setFailedReason(l.getFailedReason());
                orderDetail.setStartTime(l.getStartTime());
                orderDetail.setItemKey(l.getItemKey());
                orderDetailService.add(orderDetail);

//            BusinessConfig businessConfig = new BusinessConfig();
//            businessConfig.setBusinessId(l.getBusinessId());
//            businessConfig.setKeyRule(l.getBusinessId().toString());
//            businessConfigService.update(businessConfig);
                log.info(l.getEventId()+"记录成功");
                result ="1";
            }else {
                result ="1";
            }
        }
        return result;
    }
}